package com.jihox.abookpro.fragment;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.LoginActivity;
import com.jihox.abookpro.MyApplication;
import com.jihox.abookpro.R;
import com.jihox.abookpro.adapter.OrdersListAdapter;
import com.jihox.abookpro.domain.OrderListItem;
import com.jihox.abookpro.domain.OrderListItem.Logisticvo;
import com.jihox.abookpro.domain.OrderListItem.OrderItem;
import com.jihox.abookpro.domain.OrderListItem.ShippingTypeVo;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.uploader.OnProgressListener;
import com.jihox.abookpro.uploader.UploadService;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.view.JHProgressDialog;

public class OrderFragment extends Fragment {

	private static final String HOMEFRAGMENT = "homefragment";
	private static final int HOME_CODE = 1235321;
	
	private LinkedList<OrderListItem> listViewData;
	private ListView ordersListView;
	private LinearLayout noOrderLayout;
	public static OrdersListAdapter ordersListAdapter;
	private JHProgressDialog pd;
	private UploadService uploadService;
	private OnListDataChangeListener mListDataChangeListener;
	private String cstToken;
	private TextView tvCode;
	private String userId;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mListDataChangeListener = (OnListDataChangeListener) activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_order_list, container,
				false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		tvCode = (TextView) getActivity().findViewById(R.id.tvAccountName);
		ordersListView = (ListView) getActivity().findViewById(R.id.lvOrders);
		noOrderLayout = (LinearLayout) getActivity().findViewById(R.id.llNoOrder);
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		userId = MyApplication.getInstance().getUserId();
		tvCode.setText(userId);
		cstToken = MyApplication.getInstance().getCstToken();
		initListView();
		Intent sIntent = new Intent();
		ComponentName cn = new ComponentName(getActivity(),
				"com.jihox.abookpro.uploader.UploadService");
		sIntent.setComponent(cn);
		getActivity().startService(sIntent);
		getActivity().bindService(sIntent, conn, Context.BIND_AUTO_CREATE);
	}

	@Override
	public void onPause() {
		super.onPause();
		if (uploadService != null) {
			uploadService.setOnProgressListener(null);
		}

		getActivity().unbindService(conn);
		
		if (ordersListAdapter!=null){
			if (listViewData!=null){
				for(OrderListItem item : listViewData)
				{
					item.setInUpload(false);
				}
			}
			//ordersListAdapter.notifyDataSetChanged();
		}
	}

	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// 返回一个MsgService对象
			uploadService = ((UploadService.UploadBinder) service).getService();
			// 注册回调接口来接收下载进度的变化
			uploadService.setOnProgressListener(new OnProgressListener() {
				@Override
				public void onProgress(String orderId, int status,
						int progress, List<String> waitingOrders) {
					// Log.d("AccountActivity", "OrderId = " + orderId +
					// ", progress = " + progress);
					ordersListAdapter.updateProgressBar(orderId, progress,
							status, waitingOrders);
				}
			});
			if (ordersListAdapter!=null){
				ordersListAdapter.setUploadService(uploadService);
			}
		}
	};

	private void initListView() {
		pd = JHProgressDialog.show(getActivity(), null, getResources()
				.getString(R.string.T_Loading));
		initListData();
		
		ordersListAdapter = new OrdersListAdapter(getActivity(), listViewData,
				mListDataChangeListener);
		ordersListView.setAdapter(ordersListAdapter);
	}

	private void initListData() {
		listViewData = new LinkedList<OrderListItem>();
		
		new Thread(getOrdersRunnable).start();
		// OrderDAO orderHelper = new OrderDAO(this);
		// List<Order> localOrders = orderHelper.getOrderInfoList();
		// for(Order order : localOrders)
		// {
		// OrderListItem orderItem = new OrderListItem();
		// orderItem.setOrderId(order.getOrderId());
		// listViewData.add(orderItem);
		// }
	}

	private LinkedList<OrderListItem> parseOrders(JSONArray resultJsons) {

		if (resultJsons != null) {
			LinkedList<OrderListItem> orders = new LinkedList<OrderListItem>();
			for (int i = 0; i < resultJsons.length(); i++) {
				OrderListItem order = null;
				try {
					JSONObject orderJson = resultJsons.getJSONObject(i);
					order = new OrderListItem();
					order.setAddress(orderJson.getString("completeAddress"));
					JSONArray itemsJson = orderJson
							.getJSONArray("orderitemvos");
					if (itemsJson != null && itemsJson.length() > 0) {
						List<OrderItem> orderItems = new LinkedList<OrderItem>();
						for (int j = 0; j < itemsJson.length(); j++) {
							JSONObject itemJson = itemsJson.getJSONObject(j);
							OrderItem item = new OrderItem();
							item.setProductId(itemJson.getInt("productid"));
							item.setProductName(itemJson
									.getString("productName"));
							item.setNumber(itemJson.getInt("number"));
							item.setItemPrice((float) itemJson
									.getDouble("orderitemprice"));
							item.setPrice((float) itemJson.getJSONObject(
									"productVo").getDouble("price"));
							orderItems.add(item);
						}
						order.setOrderItems(orderItems);
					}

					order.setOrderId(orderJson.getString("id"));
					order.setPhone(orderJson.getString("mobile"));
					order.setReceiver(orderJson.getString("consignee"));
					order.setStatus(orderJson.getString("simplestatusText"));
					order.setTotalAmount((float) orderJson
							.getDouble("orderprice"));
					order.setCreateDate(new Date(orderJson
							.getLong("createdDate")));
					order.setDiscountAmount((float) orderJson
							.getDouble("subtractValue"));
					order.setDiscountCode(orderJson.getString("untypecoupons"));
					order.setRemark(orderJson.getString("remark"));
					JSONArray logisticArray =  orderJson.getJSONArray("logisticvos");
					if (logisticArray!=null && logisticArray.length()>0){
						List<Logisticvo> logisticvos = new ArrayList<Logisticvo>();
						for (int j=0;j<logisticArray.length();j++){
							Logisticvo logistic = new Logisticvo();
							logistic.setCode(logisticArray.getJSONObject(j).getString("code"));
							ShippingTypeVo shippingTypeVo = new ShippingTypeVo();
							shippingTypeVo.setCode(logisticArray.getJSONObject(j).getJSONObject("shippingTypeVo").getString("code"));
							logistic.setShippingTypeVo(shippingTypeVo);
							logisticvos.add(logistic);
						}
						order.setLogisticvos(logisticvos);
					}
				
					orders.add(order);
					// order.setWayBillCode();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return orders;
		}
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (ordersListAdapter != null) {
			ordersListAdapter.clearCache();
		}

	}

	private Runnable getOrdersRunnable = new Runnable() {
		private static final int REQUEST_TIMEOUT = 10 * 1000;
		private static final int SO_TIMEOUT = 10 * 1000;

		@Override
		public void run() {
//			String customerCode = MyApplication.getInstance().getCustomerCode();
			// TODO Auto-generated method stub
			String url = ConfigProperties.getOrdersListUrl().replace("{}", "0");
//			url = url
//					+ ("".equals(customerCode) || null == customerCode ? ""
//							: "?customerCode=" + customerCode);
			HttpGet httpPost = new HttpGet(url);
			UserHelper helper = new UserHelper();
//			httpPost.setHeader("username", helper.getUserName());
//			httpPost.setHeader("password", helper.getPassword());
			httpPost.setHeader("cstToken", cstToken);

			try {
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,
						REQUEST_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpPost);
				String result = EntityUtils.toString(httpResponse.getEntity());
				Log.i("msg", result);
				JSONObject responseJson = new JSONObject(result);

				if("true".equals(responseJson.getString("success"))){
					JSONArray ordersJson = responseJson.getJSONArray("Data");

					Log.i("msg_order", ordersJson.toString());
					if (ordersJson != null) {
						listViewData = parseOrders(ordersJson);
					}
					Message msg = new Message();
					msg.what = 1;
					updateListDataHandler.sendMessage(msg);
				}else{
					Log.i("msg_token", responseJson.getString("msg"));
					Message msg = new Message();
					msg.what = 2;
					updateListDataHandler.sendMessage(msg);
					
				}


			} catch (UnsupportedEncodingException e) {
				Message msg = new Message();
				msg.what = 3;
				updateListDataHandler.sendMessage(msg);
			} catch (ClientProtocolException e) {
				Message msg = new Message();
				msg.what = 4;
				updateListDataHandler.sendMessage(msg);
			} catch (IOException e) {
				e.printStackTrace();
				Message msg = new Message();
				msg.what = 5;
				updateListDataHandler.sendMessage(msg);
			} catch (JSONException e) {
				Message msg = new Message();
				msg.what = 6;
				updateListDataHandler.sendMessage(msg);
			}
		}
	};

	private Handler updateListDataHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			switch (msg.what) {
			case 1:
				if (listViewData.size() > 0) {
					mListDataChangeListener.onListDataChange(listViewData
							.size());
					noOrderLayout.setVisibility(View.GONE);
					ordersListView.setVisibility(View.VISIBLE);
				} else {
					ordersListView.setVisibility(View.GONE);
					noOrderLayout.setVisibility(View.VISIBLE);
				}
				ordersListAdapter.updateData(listViewData);
				break;
			case 2:
				Toast.makeText(getActivity(), "用户信息已过期,请重新登录", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(getActivity(),LoginActivity.class);
				intent.putExtra("comefrom", HOMEFRAGMENT);
				startActivityForResult(intent, HOME_CODE);
				break;
			default:
				Toast.makeText(getActivity(),
						getResources().getString(R.string.T_Loading_fail),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	
	public interface OnListDataChangeListener {
		public void onListDataChange(int size);
	}

}
